<template>


    <el-button type="primary"  @click="handleAdd">
       新增咨询
      </el-button>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column label="标题" prop="seekName" />
        <el-table-column label="子标题" prop="seekSubName" />
        <el-table-column label="作者" prop="seekAuth" />
        <el-table-column label="咨询类型" prop="seekType" />
        <el-table-column label="封面" prop="seekConver" >
          <template width="90" #default="scope">
          <img style="width:80px;height:80px;border:none;" :src="getServerUrl()+'/'+scope.row.seekConver">
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column align="right">
          <template #header>
        <el-input v-model="queryForm.query"  @input="initUserList" placeholder="请输入内容"></el-input>
          </template>
          <template #default="scope">
            <el-button size="small"  type="primary" @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="deleteSeek( scope.row.id)" >
             删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :size="size"
    
          background layout="prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
    
  <el-dialog v-model="dialogFormVisible" title="新增咨询" width="800" z-index="900">

  <el-form :model="seekFrom" :rules="rules" ref="seekFromRef" label-width="auto" style="max-width: 600px">
   
   <el-form-item prop="seekName" label="主题">
     <el-input v-model="seekFrom.seekName" placeholder="请输入主题"></el-input>
   </el-form-item>

   <el-form-item prop="seekSubName" label="子主题">
     <el-input v-model="seekFrom.seekSubName" placeholder="子主题"></el-input>
   </el-form-item>
   <el-form-item prop="seekAuth" label="作者">
     <el-input v-model="seekFrom.seekAuth" placeholder="作者"></el-input>
   </el-form-item>
   <el-form-item prop="seekType" label="选择类别">
     <el-select
      v-model="seekFrom.seekType"
      placeholder="Select"
      size="large"
      style="width: 240px">
      <el-option
        v-for="item in seekTypeList"
        :key="item.dictValue"
        :label="item.dictLabel"
        :value="item.dictValue"
      />
    </el-select>
   </el-form-item>
   <el-form-item prop="seekConver" label="上传封面">
    <el-input disabled v-model="seekFrom.seekConver" placeholder="上传封面"></el-input>
    <el-upload
    class="avatar-uploader"
    :action="getServerUrl()+'/seek/uploadInco'"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
   </el-form-item>

   <el-form-item prop="seekAuth" label="咨询内容">
  
    <Editor api-key="qp10bqeeopym7qvy1gn6l1dgaf7goz8wixkv99owf16ehchz" v-model="seekFrom.seekContent"   :init="init"  ></Editor>
   </el-form-item>


 </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="resetForm">取消</el-button>
            <el-button type="primary" @click=" submitForm()">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    
    </template>
    
    <script  setup>
         import {ref,reactive} from 'vue';
         import request ,{getServerUrl} from '@/util/request';
         import { ElMessage,ElMessageBox } from 'element-plus'
         import { Plus } from '@element-plus/icons-vue'
         import Editor from '@tinymce/tinymce-vue'
     
       
     const init = reactive({
      width: '100%', 
        min_height: 300, 

      images_resize_max_width: 500, // 设置图片最大宽度为500px
      images_resize_max_height: 300, // 设置图片最大高度为300px
    language:'zh_CN',
    plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave bdmap indent2em autoresize formatpainter axupimgs',
    toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
    styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
    table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight formatpainter axupimgs',


    fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
    font_formats: '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;',
   
    importcss_append: true,

    toolbar_sticky: true,
    autosave_ask_before_unload: false,

    images_upload_handler:(blobInfo) => new Promise((resolve, reject) => {
        let formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());
        request.post("seek/uploadInco",formData).then(res=>{
           if(res.data.code==0){
            resolve(getServerUrl()+'/'+res.data.data.src)
           }else{
            ElMessage.error(res.data.msg);
           }
          })
    })

 

  });

        const content=ref('')
         const dialogFormVisible = ref(false)
         const tableData=ref([]);
          const seekTypeList=ref([]);
         const total=ref(0);
         const queryForm=ref({
            query:"",
            pageNum:1,
            pageSize:10
         })

         const iniseekTypeList=async ()=>{
           const res= await request.get("dict/getListByType/seek_type")
           seekTypeList.value=res.data.data;
           
         }
         iniseekTypeList();

         const initUserList=async ()=>{
           const res= await request.post("/seek/list",queryForm.value)
           tableData.value=res.data.data.dataList;
           total.value=res.data.data.total;
         }
         initUserList();
         const handleSizeChange=(pageSize)=>{
            queryForm.value.pageNum=1;
            queryForm.value.pageSize=pageSize
            initUserList();
         }
         const handleCurrentChange=(pageNum)=>{
            queryForm.value.pageNum=pageNum;
            initUserList();
         }
     
         const seekFrom = reactive({
          id:'',
          seekName:'',
          seekSubName:'',
          seekType:'',
          seekAuth:'',
          seekConver:'',
          seekContent:''
    })
    const imageUrl=ref("")
    const seekFromRef = ref(null);
    const rules = {
      seekName: [
        { required: true, message: '请输入咨询主题', trigger: 'blur' }
      ],
      seekSubName: [
        { required: true, message: '请输入咨询副标题', trigger: 'blur' }
      ],
      seekType: [
        { required: true, message: '请选择咨询类型', trigger: 'blur' }
      ],
      seekConver: [
        { required: true, message: '请上传咨询封面', trigger: 'blur' }
      ]
      ,
      seekContent: [
        { required: true, message: '请填写咨询内容', trigger: 'blur' }
      ]
    };
    const deleteSeek=(id)=>{
  ElMessageBox.confirm(
          '确认删除',
          'Warning',
          {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
          }
      ).then(() => {
          request.get("seek/"+id).then(res=>{
            if(res.data.code==200){
              initUserList()
              ElMessage.success("删除成功")
            }else{
              ElMessage.error(res.data.msg);
            }
          })
    })}
     
    const submitForm = () => {
      seekFromRef.value.validate((valid) => {
        if (valid) {
          request.post("seek/saveOrUpdate",seekFrom).then(res=>{
           if(res.data.code==200){
            initUserList();
            resetForm();
            ElMessage.success("新增成功")
           }else{
            ElMessage.error(res.data.msg);
           }
          })
        } else {
          return false;
        }
      });
    };
    const handleEdit=(index,row)=>{
     let obj=  Object.assign({}, row)
         seekFrom.id=obj.id,
         seekFrom.seekName=obj.seekName,
         seekFrom.seekSubName=obj.seekName,
         seekFrom.seekType=obj.seekType,
         seekFrom.seekAuth=obj.seekAuth,
         seekFrom.seekConver=obj.seekConver,
         seekFrom.seekContent=obj.seekContent
     imageUrl.value= getServerUrl()+'/'+obj.seekConver;
    dialogFormVisible.value = true
    }
    
    const handleAdd=()=>{
      dialogFormVisible.value = true
    }
    
    const resetForm = () => {
      seekFrom.id='';
         seekFrom.seekName='';
         seekFrom.seekSubName='';
         seekFrom.seekType='';
         seekFrom.seekAuth='';
         seekFrom.seekConver='';
         seekFrom.seekContent='';
     imageUrl.value= '';
      dialogFormVisible.value = false
     }

const handleAvatarSuccess= (res)=>{
  imageUrl.value= getServerUrl()+'/'+res.data.src
  seekFrom.seekConver=res.data.src;
   
}


const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('图片必须是jpg格式')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2M!')
  }
  return isJPG && isLt2M
}


    </script>
    
    <style lang="scss" scoped>
    .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.your-editor {
  height: 300px;
}
    </style>
    